<template>
  <div class="wt-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="formConfig.labelWidth"
      :size="formConfig.size || 'small'"
      :disabled="formConfig.disabled"
      :inline="formConfig.inline"
      :label-position="formConfig.labelPosition"
    >
      <el-row :gutter="formConfig.gutter || 16">
        <el-col
          v-for="(item, index) in visibleFormItems"
          :key="getItemKey(item, index)"
          :span="item.span || 24"
          :xs="item.xs || 24"
          :sm="item.sm || 12"
          :md="item.md || item.span || 8"
          :lg="item.lg || item.span || 6"
          :xl="item.xl || item.span || 4"
        >
          <el-form-item
            :label="item.label"
            :prop="item.prop"
            :required="item.required"
          >
            <!-- Input 输入框 -->
            <el-input
              v-if="item.type === 'input'"
              v-model="formData[item.prop]"
              :placeholder="item.placeholder"
              :clearable="item.clearable !== false"
              :style="{ width: item.width || '100%' }"
              @change="(value) => handleItemChange(item, value, 'change')"
            />

            <!-- Select 选择器 -->
            <el-select
              v-else-if="item.type === 'select'"
              v-model="formData[item.prop]"
              :placeholder="item.placeholder"
              :clearable="item.clearable !== false"
              :filterable="item.filterable"
              :loading="itemOptionsLoading[item.prop]"
              :disabled="itemOptionsLoading[item.prop]"
              :style="{ width: item.width || '100%' }"
              @focus="handleSelectFocus(item)"
              @change="(value) => handleItemChange(item, value, 'change')"
            >
              <el-option
                v-for="(option, optionIndex) in getItemOptions(item)"
                :key="optionIndex"
                :label="option.label"
                :value="option.value"
                :disabled="option.disabled"
              />
              <!-- 加载状态 -->
              <template v-if="itemOptionsLoading[item.prop]">
                <div class="options-loading">
                  <i class="el-icon-loading"></i>
                  <span>加载中...</span>
                </div>
              </template>
            </el-select>

            <!-- Switch 开关 -->
            <el-switch
              v-else-if="item.type === 'switch'"
              v-model="formData[item.prop]"
              :active-text="item.activeText"
              :inactive-text="item.inactiveText"
              @change="(value) => handleItemChange(item, value, 'change')"
            />

            <!-- Radio 单选框 -->
            <el-radio-group
              v-else-if="item.type === 'radio'"
              v-model="formData[item.prop]"
              :style="{ width: item.width || '100%' }"
              @change="(value) => handleItemChange(item, value, 'change')"
            >
              <el-radio
                v-for="(option, optionIndex) in getItemOptions(item)"
                :key="optionIndex"
                :label="option.value"
                :disabled="option.disabled"
                :border="item.border"
              >
                {{ option.label }}
              </el-radio>
              <!-- 加载状态 -->
              <div v-if="itemOptionsLoading[item.prop]" class="options-loading">
                <i class="el-icon-loading"></i>
                <span>加载中...</span>
              </div>
            </el-radio-group>

            <!-- Checkbox 多选框 -->
            <el-checkbox-group
              v-else-if="item.type === 'checkbox'"
              v-model="formData[item.prop]"
              :style="{ width: item.width || '100%' }"
              @change="(value) => handleItemChange(item, value, 'change')"
            >
              <el-checkbox
                v-for="(option, optionIndex) in getItemOptions(item)"
                :key="optionIndex"
                :label="option.value"
                :disabled="option.disabled"
                :border="item.border"
              >
                {{ option.label }}
              </el-checkbox>
              <!-- 加载状态 -->
              <div v-if="itemOptionsLoading[item.prop]" class="options-loading">
                <i class="el-icon-loading"></i>
                <span>加载中...</span>
              </div>
            </el-checkbox-group>

            <!-- Textarea 文本域 -->
            <el-input
              v-else-if="item.type === 'textarea'"
              v-model="formData[item.prop]"
              type="textarea"
              :placeholder="item.placeholder"
              :rows="item.rows || 3"
              :maxlength="item.maxlength"
              :show-word-limit="item.showWordLimit"
              :style="{ width: item.width || '100%' }"
              @change="(value) => handleItemChange(item, value, 'change')"
            />

            <!-- Date 日期选择器 -->
            <el-date-picker
              v-else-if="item.type === 'date'"
              v-model="formData[item.prop]"
              type="date"
              :placeholder="item.placeholder || '选择日期'"
              :value-format="item.valueFormat || 'yyyy-MM-dd'"
              :style="{ width: item.width || '100%' }"
              @change="(value) => handleItemChange(item, value, 'change')"
            />

            <!-- Time 时间选择器 -->
            <el-time-picker
              v-else-if="item.type === 'time'"
              v-model="formData[item.prop]"
              :placeholder="item.placeholder || '选择时间'"
              :value-format="item.valueFormat || 'HH:mm:ss'"
              :style="{ width: item.width || '100%' }"
              @change="(value) => handleItemChange(item, value, 'change')"
            />

            <!-- Datetime 日期时间选择器 -->
            <el-date-picker
              v-else-if="item.type === 'datetime'"
              v-model="formData[item.prop]"
              type="datetime"
              :placeholder="item.placeholder || '选择日期时间'"
              :value-format="item.valueFormat || 'yyyy-MM-dd HH:mm:ss'"
              :style="{ width: item.width || '100%' }"
              @change="(value) => handleItemChange(item, value, 'change')"
            />

            <!-- 未知类型提示 -->
            <div v-else class="unknown-type">
              未知的表单类型: {{ item.type }}
            </div>
          </el-form-item>
        </el-col>

        <!-- 按钮区域 -->
        <el-col v-if="hasButtons" :style="btnStyle" :span="24">
          <div class="btns-action">
            <el-button
              v-for="(btn, index) in formConfig.buttons.options"
              :key="index"
              :type="btn.type"
              :icon="btn.icon"
              :loading="btn.loading"
              :disabled="btn.disabled"
              @click="handleButtonClick(btn)"
              :size="formConfig.size || 'small'"
            >
              {{ btn.label }}
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'WtForm',
  props: {
    formConfig: {
      type: Object,
      default: () => ({}),
      validator: config => {
        return !config.formItems || Array.isArray(config.formItems)
      }
    }
  },
  data() {
    return {
      formData: {},
      itemVisibleState: {},
      // 存储各表单项的选项数据
      itemOptionsData: {},
      // 存储各表单项的加载状态
      itemOptionsLoading: {},
      // 存储已加载过的表单项，避免重复加载
      loadedItems: new Set()
    }
  },
  computed: {
    formRules() {
      return this.formConfig.rules || {}
    },

    visibleFormItems() {
      if (!Array.isArray(this.formConfig.formItems)) {
        return []
      }
      return this.formConfig.formItems.filter(item => {
        if (item.showCondition) {
          return item.showCondition(this.formData, this.itemVisibleState)
        }
        return item.hidden !== true
      })
    },

    hasButtons() {
      return (
        this.formConfig.buttons &&
        Array.isArray(this.formConfig.buttons.options) &&
        this.formConfig.buttons.options.length > 0
      )
    },

    btnStyle() {
      const style = {}
      const alignMap = {
        left: 'flex-start',
        center: 'center',
        right: 'flex-end'
      }

      const { buttons } = this.formConfig
      if (buttons && buttons.flex) {
        style.display = 'flex'
        style.flex = buttons.flex
      }
      if (buttons && buttons.align) {
        style.justifyContent = alignMap[buttons.align] || 'flex-end'
      }
      return style
    }
  },
  watch: {
    formData: {
      handler(newVal) {
        this.$emit('change', newVal)
      },
      deep: true
    }
  },
  created() {
    this.initFormData()
    // 初始化时加载需要预加载的选项
    this.preloadOptions()
  },
  methods: {
    getItemKey(item, index) {
      return item.prop || `form-item-${index}`
    },

    initFormData() {
      const { formItems } = this.formConfig
      if (!Array.isArray(formItems)) return

      formItems.forEach(item => {
        let defaultValue = item.defaultValue

        if (defaultValue === undefined) {
          switch (item.type) {
            case 'checkbox':
              defaultValue = []
              break
            case 'switch':
              defaultValue = false
              break
            case 'radio':
            case 'select':
              // 先判断 options 的类型
              if (Array.isArray(item.options)) {
                // options 是数组
                if (item.options.length > 0) {
                  defaultValue = item.options[0].value
                } else {
                  defaultValue = ''
                }
              } else if (typeof item.options === 'function') {
                // options 是函数，无法立即获取默认值，使用空值
                defaultValue = ''
              } else {
                // 其他情况（如 undefined、null 等）
                defaultValue = ''
              }
              break
            default:
              defaultValue = ''
          }
        }

        this.$set(this.formData, item.prop, defaultValue)
      })
    },
    // 预加载需要立即加载的选项
    async preloadOptions() {
      const { formItems } = this.formConfig
      if (!Array.isArray(formItems)) return

      for (const item of formItems) {
        // 如果配置了 autoLoad 为 true，则在创建时自动加载
        if (item.autoLoad && this.isOptionsFunction(item.options)) {
          await this.loadItemOptions(item)
        }
      }
    },

    // 判断 options 是否是函数
    isOptionsFunction(options) {
      return typeof options === 'function'
    },

    // 获取表单项的选项数据
    getItemOptions(item) {
      // 如果 options 是数组，直接返回
      if (Array.isArray(item.options)) {
        return item.options
      }

      // 如果 options 是函数，返回缓存的选项数据
      if (this.isOptionsFunction(item.options)) {
        return this.itemOptionsData[item.prop] || []
      }

      return []
    },

    // 处理 select 聚焦事件（触发加载选项）
    async handleSelectFocus(item) {
      if (
        this.isOptionsFunction(item.options) &&
        !this.loadedItems.has(item.prop)
      ) {
        await this.loadItemOptions(item)
      }
    },

    // 加载表单项的选项数据
    async loadItemOptions(item) {
      if (!this.isOptionsFunction(item.options)) return

      const { prop } = item

      // 设置加载状态
      this.$set(this.itemOptionsLoading, prop, true)

      try {
        // 执行 options 函数
        const result = item.options(this.formData)

        // 处理 Promise 或同步返回值
        const options = result instanceof Promise ? await result : result

        // 缓存选项数据
        this.$set(
          this.itemOptionsData,
          prop,
          Array.isArray(options) ? options : []
        )

        // 标记为已加载
        this.loadedItems.add(prop)

        this.$emit('options-loaded', prop, options)
      } catch (error) {
        console.error(`加载选项失败 ${prop}:`, error)
        this.$set(this.itemOptionsData, prop, [])
        this.$emit('options-error', prop, error)
      } finally {
        this.$set(this.itemOptionsLoading, prop, false)
      }
    },

    // 手动重新加载选项
    async reloadOptions(prop) {
      const item = this.formConfig.formItems.find(item => item.prop === prop)
      if (item && this.isOptionsFunction(item.options)) {
        this.loadedItems.delete(prop)
        await this.loadItemOptions(item)
      }
    },

    // 批量重新加载选项
    async reloadAllOptions() {
      const { formItems } = this.formConfig
      if (!Array.isArray(formItems)) return

      for (const item of formItems) {
        if (this.isOptionsFunction(item.options)) {
          this.loadedItems.delete(item.prop)
          await this.loadItemOptions(item)
        }
      }
    },

    handleItemChange(item, value) {
      this.$emit('item-change', item.prop, value, this.formData)

      if (item.onChange) {
        item.onChange(value, this.formData)
      }
    },

    handleButtonClick(btn) {
      const actions = {
        submit: () => this.submitForm(btn.onClick),
        reset: () => this.resetForm(btn.onClick),
        custom: () => btn.onClick && btn.onClick(this.formData)
      }

      const action = actions[btn.action] || actions.custom
      action()
    },

    getFormData() {
      return { ...this.formData }
    },

    setFormData(data) {
      Object.keys(data).forEach(key => {
        if (this.formData[key] !== undefined) {
          this.$set(this.formData, key, data[key])
        }
      })
    },

    async submitForm(callback) {
      try {
        const valid = await this.$refs.formRef.validate()
        if (valid) {
          this.$emit('submit', this.formData)
          callback && callback(this.formData)
          return true
        }
      } catch (error) {
        this.$emit('validate-error', error)
        console.error('表单验证失败:', error)
        return false
      }
    },

    resetForm(callback) {
      this.initFormData()
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
      this.$emit('reset')
      callback && callback()
    },

    clearValidate(props) {
      this.$refs.formRef.clearValidate(props)
    },

    validateField(props) {
      return this.$refs.formRef.validateField(props)
    }
  }
}
</script>

<style scoped lang="scss">
.wt-form {
  .el-row {
    display: flex;
    flex-wrap: wrap;

    .el-col {
      margin-bottom: 16px;

      @media (max-width: 768px) {
        margin-bottom: 12px;
      }
    }
  }

  .btns-action {
    padding-top: 8px;
    text-align: right;

    .el-button + .el-button {
      margin-left: 12px;
    }
  }

  .unknown-type {
    color: #f56c6c;
    font-size: 12px;
    padding: 8px;
    background: #fef0f0;
    border-radius: 4px;
  }

  .options-loading {
    text-align: center;
    padding: 8px;
    color: #909399;
    font-size: 12px;

    .el-icon-loading {
      margin-right: 5px;
    }
  }
}
</style>
